package com.kaishengit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kaishengit.entity.Order;
import com.kaishengit.util.DBHelp;

public class OrderDao {

	private DBHelp<Order> db = new DBHelp<Order>();
	
	public void save(Order order) {
		String sql = "INSERT INTO t_order(id,address,tel,`name`,createtime,state,userid) VALUES(?,?,?,?,?,?,?)";
		db.executeSQL(sql, order.getId(),order.getAddress(),order.getTel(),order.getName(),order.getCreatetime(),order.getState(),order.getUserid());
	}
	
	public List<Map<String,Object>> findByUserId(int userid) {
		String sql = "SELECT id,createtime,state,(SELECT SUM(total) FROM t_orderitem WHERE orderid = t_order.id) AS 'total' FROM t_order WHERE userid = ?";
		Connection conn = db.getConnection();
		PreparedStatement stat = null;
		ResultSet rs = null;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			stat = conn.prepareStatement(sql);
			stat.setInt(1, userid);
			
			rs = stat.executeQuery();
			
			while(rs.next()) {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("id", rs.getString("id"));
				map.put("createtime", rs.getString("createtime"));
				map.put("state", rs.getString("state"));
				map.put("total", rs.getFloat("total"));
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.close(rs, stat, conn);
		}
		return list;
	}
}
